#ifndef __DOCUMENT_H__
#define __DOCUMENT_H__

#include <vector>

namespace invertedindex{

class Document{
	private:
		unsigned int id;
		unsigned int numberOfOccurrences;
		typedef std::vector<unsigned int> Positions;
		Positions ptns;
	public:
		Document(unsigned int id){
			this->id=id;
			numberOfOccurrences=0;
		}

		Document(const Document& dc){
			this->id=dc.getId();
			this->numberOfOccurrences = dc.getNumberOfOccurrences();
			unsigned int i;
			for(i=0; i<this->numberOfOccurrences; i++){
				ptns.insert(ptns.end(),dc.getPosition(i).second);
			}
		}

		~Document(){
			//TODO liberar vector
		}

		void setId(unsigned int id){this->id = id;}
		unsigned int getId()const{return id;}

		unsigned int getNumberOfOccurrences()const{return numberOfOccurrences;}
	
		std::pair<bool, unsigned int> getPosition(unsigned int index)const{
			std::pair<bool, unsigned int> ret(false,0);
			if(ptns.size()>index){
				ret.second=(ptns.at(index));
				ret.first=true;
			}
			return ret;
		}

		bool insertPosition(unsigned int position)
		{
			bool encontro = false;
			Positions::iterator it = ptns.begin();
			unsigned int i=0;
			while((i<ptns.size())&&(!encontro)){
				if((*it)>=position){
					encontro=true;
				}
				else{
					i++;
					it++;
				}
			}
			if(!((encontro)&&((*it)==position))){
				if(encontro==false)
					it=ptns.end();
				Positions::iterator p=ptns.insert(it,position);
				if(*p==position){
					numberOfOccurrences++;
					return true;
				}
				std::cout<<"OP1"<<numberOfOccurrences<<std::endl;
				return false;
			}
			std::cout<<"OP2"<<numberOfOccurrences<<std::endl;
			return false;
		}

		bool removePosition(unsigned int position)
		{
			bool encontro = false;
			Positions::iterator it = ptns.begin();
			unsigned int i=0;
			while((i<ptns.size())&&(!encontro)){
				if((*it)<=position){
					encontro=true;
				}
				else{
					i++;
					it++;
				}
			}

		
			if((it!=ptns.end())&&((*it)==position)){
				ptns.erase(it);
				numberOfOccurrences--;
				return true;
			}

			return false;
		}

		Document* duplicate()const{
			return (new Document(*this));
		}

		std::ostream& toOstream(std::ostream& out)const{
			out<<"\tidDoc:"<<this->id<<std::endl;
			out<<"\tnumberOfOccurrences:"<<this->numberOfOccurrences<<std::endl;
			unsigned int i=0;
			while(i<ptns.size()){
				out<<"\t position["<<i<<"]:"<<ptns[i]<<std::endl;
				i++;
			}
			return out;
		}

		bool operator ==(const Document& doc)const{
			bool ret=true;
			unsigned int i=0;
			while((i<ptns.size())&&(i<doc.ptns.size())&&ret){
				if(ptns[i]!=doc.ptns[i])
					ret=false;
				i++;
			}
			if((i<ptns.size())||(i<doc.ptns.size()))
				ret=false;
			return ret;
		}

};


}

#endif


